7

What Is an Algorithm?

7

The dictionary meaning of “optimized” is “make the best or most effective use

of a situation, opportunity, or resource”. Optimized is a quality that is the hardest to

understand. Optimized can mean many things based on the “situation, opportunity or

resource” that is optimized. For example, the Tesla model 3 is the most fuel-​efficient

car in the “midsize” class of cars in 2020, as determined by fueleconomy.gov. Note

that I had to qualify this statement by the year and the “class”. Even in 2020, the most

fuel-​efficient class of “compact” cars is not Tesla—​it is Volkswagen e-​Golf. And the

most fuel-​efficient “midsize” car in 2015 was Nissan Leaf.

The point I want you to take away from this discussion is that no good quality is an

absolute value. True for life as well, the qualities that make the evaluation of anything

“good” or “bad” are bound by the parameters that are used to judge them.

We will discuss these qualities further in the next few chapters, as we dive deep

into the programs that I will introduce to get you inspired.

So why do we need algorithms?

Algorithms are to program development what a recipe is to the preparation of a

dish—​a bit more in some respects and a bit less in others.

An algorithm for a program describes how the code needs to be written in concep­

tual terms.

Even though there is no precise measurement like a recipe, an algorithm is a docu­

mentation of technique that is indispensable for the programmer. Just as you cannot

make cookies without a recipe, you cannot write a program that solves a specific

problem without an algorithm.

An algorithm usually has six parts to it:

• Inputs

• Outputs

• Variables

• Statements

• Conditional Statements

• Repetitions

The input is what is available for the processor to work with—​for example, the flour

and the sugar.

The output is the cookie but can be other things as well, such as a timer that chimes

when the cooking is done (audible output), or the mixers and plates that need to be

washed after the cookie is made (visible outputs).

Variables are receptacles that temporarily store something so that you can

remember it or use it later on. For example, you have a glass of water and you need

to use only half of it now and half later. You will need another glass to pour the other

half until you need it. Now suppose that you do not have a measuring stick to measure

the height of the glass, and you do not want to rely on your judgment to determine

whether it is exactly half—​what do you do? You get another glass that looks exactly

like the other two glasses. You pour the full glass into the two empty ones and check